<?php

namespace app\admin\controller\common;

use app\admin\controller\Base;
use app\common\model\FileModel;

class Upload extends Base
{
    /**
     * 图片上传
     */
    public function upload()
    {
        $params = request()->only(['is_vue']);

        $file = request()->file('file');
        //校验文件大小
        validate(['file' => 'fileSize:1048576|fileExt:jpg,jpeg,png,gif'])->check(['file' => $file]);

        //简单防止php注入
        if ($file->extension() == 'php') {
            return response_error('系统异常，请联系管理员');
        }

        //保存文件到本地并写入数据库
        $path = 'uploads/' . date('Y') . '/' . date('m') . '/' . date('d');
        $fileName = md5(uniqid()) . '.' . $file->extension();
        $filePath = \think\facade\Filesystem::disk('public')->putFileAs($path, $file, $fileName);
        $temp = [
            'name' => $file->getOriginalName(),
            'path' => 'storage/' . str_replace('\\', '/', $filePath),
            'type' => FileModel::TYPE_IMG,
            'size' => filesize($file),
            'ext' => $file->extension(),
            'create_admin_id' => $this->adminInfo['id'],
            'create_time' => date('Y-m-d H:i:s')
        ];
        $temp['id'] = (new FileModel)->insertGetId($temp);
        $temp['url'] = get_file_url($temp['path']);

        if (isset($params['is_vue']) && $params['is_vue'] == 1) {
            return json([
                'message' => 'success',
                'errno' => 0,
                'data' => [
                    'url' => $temp['url'],
                    'alt' => '',
                    'href' => '',
                ]
            ]);
        }

        return response_success('', $temp);
    }

}